// MultiLevelPickerView.m
#import "MultiLevelPickerView.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kPickerHeight 250
#define kToolbarHeight 44

@interface MultiLevelPickerView () <UIPickerViewDelegate, UIPickerViewDataSource> {
    NSMutableArray *_dataSources;    // 每一级的数据源
    NSMutableArray *_selectedIndexes; // 每一级选中的索引
}

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UIBarButtonItem *cancelButton;
@property (nonatomic, strong) UIBarButtonItem *confirmButton;
@property (nonatomic, strong) UIBarButtonItem *titleLabel;

@property (nonatomic, copy) MultiLevelPickerCompletionBlock completionBlock;
@property (nonatomic, copy) MultiLevelPickerCancelBlock cancelBlock;
@property (nonatomic, copy) MultiLevelPickerIndexChangedBlock indexChangedBlock;
@property (nonatomic, copy) MultiLevelPickerDataRequestBlock requestDataBlock;

@end

@implementation MultiLevelPickerView

#pragma mark - 初始化方法

- (instancetype)initWithFirstLevelData:(NSArray *)firstLevelData
                     secondLevelData:(NSArray *)secondLevelData
                      thirdLevelData:(NSArray *)thirdLevelData {
    self = [super initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    if (self) {
        _dataSources = [NSMutableArray arrayWithCapacity:3];
        _selectedIndexes = [NSMutableArray arrayWithCapacity:3];
        self.title = @"三级选择器";
        self.toolbarBackgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
        self.titleColor = [UIColor darkTextColor];
        self.buttonColor = [UIColor colorWithRed:0.0 green:0.478 blue:1.0 alpha:1.0];
        
        // 初始化数据源
        _dataSources[0] = [firstLevelData mutableCopy] ?: [@[@"请选择"] mutableCopy];
        _dataSources[1] = [secondLevelData mutableCopy] ?: @[];
        _dataSources[2] = [thirdLevelData mutableCopy] ?: @[];
        
        // 初始化选中索引
        for (NSInteger i = 0; i < 3; i++) {
            [_selectedIndexes addObject:@(0)];
        }
        
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    // 背景遮罩
    self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
    self.backgroundView.backgroundColor = [UIColor blackColor];
    self.backgroundView.alpha = 0;
    [self addSubview:self.backgroundView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.backgroundView addGestureRecognizer:tapGesture];
    
    // 容器视图
    self.containerView = [[UIView alloc] init];
    self.containerView.backgroundColor = [UIColor whiteColor];
    self.containerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kPickerHeight + kToolbarHeight);
    [self addSubview:self.containerView];
    
    // 工具栏
    self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kToolbarHeight)];
    self.toolbar.barStyle = UIBarStyleDefault;
    self.toolbar.translucent = NO;
    self.toolbar.backgroundColor = self.toolbarBackgroundColor;
    [self.containerView addSubview:self.toolbar];
    
    // 取消按钮
    self.cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonClicked)];
    
    // 确认按钮
    self.confirmButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(confirmButtonClicked)];
    
    // 标题
    self.titleLabel = [[UIBarButtonItem alloc] initWithTitle:@"级联选择器" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.titleLabel.enabled = NO;
    
    // 设置工具栏按钮
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [self.toolbar setItems:@[flexibleSpace,self.cancelButton, flexibleSpace,flexibleSpace,flexibleSpace, self.titleLabel, flexibleSpace,flexibleSpace,flexibleSpace, self.confirmButton,flexibleSpace] animated:NO];
    
    // PickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kToolbarHeight, kScreenWidth, kPickerHeight)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.containerView addSubview:self.pickerView];
}

#pragma mark - 公共方法

+ (instancetype)showPickerWithFirstLevelData:(NSArray *)firstLevelData
                         secondLevelData:(NSArray *)secondLevelData
                          thirdLevelData:(NSArray *)thirdLevelData
                                    title:(NSString *)title
                               completion:(MultiLevelPickerCompletionBlock)completion
                                onCancel:(MultiLevelPickerCancelBlock)cancel
                        indexChanged:(MultiLevelPickerIndexChangedBlock)indexChanged
                         requestData:(MultiLevelPickerDataRequestBlock)requestData {
    MultiLevelPickerView *picker = [[MultiLevelPickerView alloc] initWithFirstLevelData:firstLevelData
                                                                     secondLevelData:secondLevelData
                                                                      thirdLevelData:thirdLevelData];
    picker.title = title ?: @"三级选择器";
    [picker showWithCompletion:completion onCancel:cancel indexChangedBlock:indexChanged requestData:requestData];
    return picker;
}

- (void)showWithCompletion:(MultiLevelPickerCompletionBlock)completion
                   onCancel:(MultiLevelPickerCancelBlock)cancel
           indexChangedBlock:(MultiLevelPickerIndexChangedBlock)indexChanged
                requestData:(MultiLevelPickerDataRequestBlock)requestData {
    self.completionBlock = [completion copy];
    self.cancelBlock = [cancel copy];
    self.indexChangedBlock = [indexChanged copy];
    self.requestDataBlock = [requestData copy];
    
    // 更新标题
    self.titleLabel.title = self.title;
    
    // 显示选择器
    [self show];
    
    // 刷新PickerView
    for (NSInteger i = 0; i < 3; i++) {
        [self.pickerView reloadComponent:i];
    }
    
    // 自动加载数据
    [self loadInitialData];
}

#pragma mark - 数据加载

- (void)loadInitialData {
    // 如果第二级数据为空且有请求块，请求第二级数据
    NSArray *arr1 = _dataSources[1];
    NSArray *arr2 = _dataSources[0];
    if (arr1.count == 0 && self.requestDataBlock && arr2.count > 0) {
        [self loadDataForLevel:1];
    }
}

- (void)loadDataForLevel:(NSInteger)level {
    // 构建已选中的值数组
    NSMutableArray *selectedValues = [NSMutableArray arrayWithCapacity:level];
    for (NSInteger i = 0; i < level; i++) {
        NSInteger index = [_selectedIndexes[i] integerValue];
        NSArray *levelData = _dataSources[i];
        if (index < levelData.count) {
            [selectedValues addObject:levelData[index]];
        } else {
            [selectedValues addObject:@""];
        }
    }
    
    // 请求数据
    self.requestDataBlock(level, selectedValues, ^(NSArray *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->_dataSources[level] = [data mutableCopy];
            [self.pickerView reloadComponent:level];
            if(level+1 < self->_dataSources.count){
                NSArray *arr = self->_dataSources[level+1];
                // 如果不是最后一级且下一级数据为空，继续请求下一级数据
                if (level < 2 && arr.count == 0 && data.count > 0) {
                    [self loadDataForLevel:level+1];
                }
            }
            
        });
    });
}

#pragma mark - 显示和隐藏方法

- (void)show {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0.4;
        CGRect frame = self.containerView.frame;
        frame.origin.y = kScreenHeight - frame.size.height;
        self.containerView.frame = frame;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0;
        CGRect frame = self.containerView.frame;
        frame.origin.y = kScreenHeight;
        self.containerView.frame = frame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 按钮点击事件

- (void)cancelButtonClicked {
    [self dismiss];
    
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

- (void)confirmButtonClicked {
    [self dismiss];
    
    // 构建选中的值数组
    NSMutableArray *selectedValues = [NSMutableArray arrayWithCapacity:3];
    for (NSInteger i = 0; i < 3; i++) {
        NSInteger index = [_selectedIndexes[i] integerValue];
        NSArray *levelData = _dataSources[i];
        if (index < levelData.count) {
            [selectedValues addObject:levelData[index]];
        } else {
            [selectedValues addObject:@""];
        }
    }
    
    // 回调结果
    if (self.completionBlock) {
        self.completionBlock(selectedValues, [_selectedIndexes copy]);
    }
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3; // 固定三级
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component < _dataSources.count) {
        NSArray *data = _dataSources[component];
        return data.count > 0 ? data.count : 1; // 无数据时显示一行
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate

// 移除原有的 attributedTitleForRow 方法，替换为：
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:16.0]; // 设置字体大小
        label.textColor = main_text_color; // 设置文字颜色
        label.adjustsFontSizeToFitWidth = YES;
        label.minimumScaleFactor = 0.8;
    }
    
    NSString *title = @"";
        if (component < _dataSources.count) {
            NSArray *data = _dataSources[component];
            if (data.count > 0) {
                title =  row < data.count ? data[row] : @"无数据";
            }
        }
    
    label.text = title;
    return label;
}

// 必须实现行高方法
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 44.0; // 根据字体大小调整行高
}
//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//    if (component < _dataSources.count) {
//        NSArray *data = _dataSources[component];
//        if (data.count > 0) {
//            return row < data.count ? data[row] : @"无数据";
//        }
//    }
//    return @"请选择";
//}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    // 更新选中索引
    _selectedIndexes[component] = @(row);
    
    // 回调索引变化
    if (self.indexChangedBlock) {
        self.indexChangedBlock(component, row);
    }
    
    // 如果有请求块且不是最后一级，清空后续级别并请求数据
    if (self.requestDataBlock && component < 2) {
        // 清空后续级别数据
        for (NSInteger i = component + 1; i < 3; i++) {
            _dataSources[i] = @[];
            _selectedIndexes[i] = @(0);
            [self.pickerView reloadComponent:i];
        }
        
        // 请求下一级数据
        [self loadDataForLevel:component + 1];
    }
}

@end
